package com.example.app_mqttclient;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.app_mqttclient.activity.BlockToysActivity;
import com.example.app_mqttclient.activity.DeviceChooseActivity;
import com.example.app_mqttclient.activity.LightDevActivity;
import com.example.app_mqttclient.activity.UserSettingActivity;
import com.example.app_mqttclient.adapter.MyAdapter;
import com.example.app_mqttclient.broadcast.MyBroadcast;
import com.example.app_mqttclient.obj.DeviceView;
import com.example.app_mqttclient.obj.MqttData;
import com.example.app_mqttclient.obj.MyMqttClient;
import com.example.app_mqttclient.service.MyService;
import com.example.app_mqttclient.sqlite.MyDBOpenHelper;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";

    private int winWidth;
    private int winHeight;
    // adapter 动态添加组件相关
    private GridView deviceGridView;
    public static MyAdapter<DeviceView> deviceAdapter = null;
    public static List<DeviceView> deviceData = null;
    // 广播
    public static LocalBroadcastManager localBroadcastManager;
    private MyBroadcast myBroadcast;

    private MyDBOpenHelper myDBHelper;
    private SQLiteDatabase db;
    private int i = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取屏幕宽高
        WindowManager wm = this.getWindowManager();
        winWidth = wm.getDefaultDisplay().getWidth();
        winHeight = wm.getDefaultDisplay().getHeight();

        // 启动mqtt client
        MyMqttClient.beginMqttClient();

        // 创建数据库
        myDBHelper = new MyDBOpenHelper(MainActivity.this, "myMqttClient.db", null, 1);
        db = myDBHelper.getWritableDatabase();

        /************使用adapter动态创建组件*************/
        deviceGridView = (GridView) findViewById(R.id.main_grid_container);
        deviceData = new ArrayList<DeviceView>();
        initDeviceViewFromDB();
        deviceAdapter = new MyAdapter<DeviceView>((ArrayList)deviceData, R.layout.layout_device_view) {
            @Override
            public void bindView(ViewHolder holder, DeviceView obj) {
                MyMqttClient.mqttSubscribe(obj.getDevicePubTopic(), 1); // 订阅mqtt主题
                // 调用内部类暴露的方法去设置组件属性
                holder.setImageResource(R.id.device_view_device_img, obj.getDeviceImg());
                holder.setText(R.id.device_view_device_name, obj.getDeviceName());
                holder.setText(R.id.device_view_device_state, obj.getDeviceState() == false ? "离线" : "在线");
                holder.setOnClickListener(R.id.device_view_container, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // 通过Bundle传递数据
                        Intent deviceHandleIntent;
                        Bundle bundle = new Bundle();
                        MqttData mqttData = new MqttData(obj.getDevicePubTopic(), obj.getDeviceSubTopic());
                        bundle.putSerializable("mqttData", mqttData); // 继承Serializable类可以通过bundle传递类对象
                        switch(obj.getDeviceImg())
                        {
                            case R.drawable.lightbulb:
                                deviceHandleIntent = new Intent(MainActivity.this, LightDevActivity.class); // 通过Intent创建另一个Activity
                                break;
                            case R.drawable.lightoutline:
                                deviceHandleIntent = new Intent(MainActivity.this, LightDevActivity.class);
                                break;

                            case R.drawable.block:
                                deviceHandleIntent = new Intent(MainActivity.this, BlockToysActivity.class);
                                break;
                            default:
                                deviceHandleIntent = new Intent(MainActivity.this, LightDevActivity.class);
                                break;
                        }
                        deviceHandleIntent.putExtras(bundle); // 将Bundle传入Intent
                        startActivity(deviceHandleIntent); // 启动Activity
                    }
                });
            }
        };
        deviceGridView.setAdapter(deviceAdapter); // 绑定适配器

        // 实例化LocalBroadcastManager 本地广播管理者
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        //初始化广播接收者，设置过滤器
        myBroadcast = new MyBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.app_mqttclient.MQTT_RECV_DATA");
        localBroadcastManager.registerReceiver(myBroadcast, intentFilter); // 绑定广播接收

        // 开启服务
//        Intent serviceIntent = new Intent(MainActivity.this, MyService.class);
//        startService(serviceIntent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String deviceName = data.getStringExtra("deviceName");
        int deviceImgID = data.getIntExtra("deviceImgID", R.id.device_choose_btn_normal_light);
        String devicePubTopic = data.getStringExtra("publishTopic");
        String deviceSubTopic = data.getStringExtra("subscribeTopic");
        // 创建设备主视图
        createDeviceView(deviceName, deviceImgID, devicePubTopic, deviceSubTopic);
    }

    private void createDeviceView(String deviceName, int deviceImgID, String devicePubTopic, String deviceSubTopic)
    {
        if(deviceName.isEmpty() || devicePubTopic.isEmpty() || deviceSubTopic.isEmpty())
        {
            Log.e(TAG, "device name or device publish topic or device subscribe topic is null!");
            return;
        }
        MyMqttClient.mqttSubscribe(devicePubTopic, 1); // 订阅mqtt主题
        // 添加新的deviceView
        deviceData.add(new DeviceView(deviceImgID, deviceName, false, devicePubTopic, deviceSubTopic));
        deviceAdapter.notifyDataSetChanged(); // adapter内容更新
        // 写入数据库
        ContentValues values = new ContentValues();
        values.put("IMG_NUM", deviceImgID);
        values.put("DEV_NAME", deviceName);
        values.put("PUB_TOPIC", devicePubTopic);
        values.put("SUB_TOPIC", deviceSubTopic);
        db.insert("ASMQTTCLIENT", null, values);
    }

    @SuppressLint("ResourceType")
    public void mainActivityOnClick(View view)
    {
        switch (view.getId())
        {
            case R.id.main_btn_user_setting:
                // 新建Activity页面 Activity页面对象(UserSettingActivity.class)
                Intent userSetting = new Intent(MainActivity.this, UserSettingActivity.class);
                // 启动Activity页面
                startActivity(userSetting);
                Log.i(TAG, "user setting btn onClick");
                break;
            case R.id.main_btn_device_add:
                // 新建Activity页面 Activity页面对象(DeviceChooseActivity.class)
                Intent deviceChoose = new Intent(MainActivity.this, DeviceChooseActivity.class);
                // 启动Activity页面
                startActivityForResult(deviceChoose, 11);
                Log.i(TAG, "device add btn onClick");
                break;
            case R.id.main_btn_test1:

                Log.i(TAG, "test1 btn onClick");
                break;
            case R.id.main_btn_test2:

                Log.i(TAG, "test2 btn onClick");
                break;
        }
    }

    private void initDeviceViewFromDB()
    {
        // 获取游标
        Cursor cursor = db.query("ASMQTTCLIENT", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                int pid = cursor.getInt(cursor.getColumnIndexOrThrow("AS_ID"));
                int imgNum = cursor.getInt(cursor.getColumnIndexOrThrow("IMG_NUM"));
                String name = cursor.getString(cursor.getColumnIndexOrThrow("DEV_NAME"));
                String pubTopic = cursor.getString(cursor.getColumnIndexOrThrow("PUB_TOPIC"));
                String subTopic = cursor.getString(cursor.getColumnIndexOrThrow("SUB_TOPIC"));
                this.deviceData.add(new DeviceView(imgNum, name, false, pubTopic, subTopic));
                Log.i(TAG, "find device view data from DB, " + pid);
            } while (cursor.moveToNext());
        }
        cursor.close();
    }

    public static Activity getActivity() {
        Class activityThreadClass = null;
        try {
            activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
            Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
            activitiesField.setAccessible(true);
            Map activities = (Map) activitiesField.get(activityThread);
            for (Object activityRecord : activities.values()) {
                Class activityRecordClass = activityRecord.getClass();
                Field pausedField = activityRecordClass.getDeclaredField("paused");
                pausedField.setAccessible(true);
                if (!pausedField.getBoolean(activityRecord)) {
                    Field activityField = activityRecordClass.getDeclaredField("activity");
                    activityField.setAccessible(true);
                    Activity activity = (Activity) activityField.get(activityRecord);
                    return activity;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(myBroadcast); // 解绑广播接收
    }
}